package com.lekang.le.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.lekang.common.annotation.Log;
import com.lekang.common.annotation.Anonymous;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.le.domain.OrderManagement;
import com.lekang.le.domain.OrderVO;
import com.lekang.le.domain.OrderCreateDTO;
import com.lekang.le.service.IOrderManagementService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 订单管理Controller
 * 
 * @author yyh
 * @date 2025-10-14
 */
@RestController
@RequestMapping("/le/management")
@CrossOrigin
public class OrderManagementController extends BaseController
{
    @Autowired
    private IOrderManagementService orderManagementService;

    /**
     * 查询订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('le:management:list')")
    @GetMapping("/list")
    public TableDataInfo list(OrderManagement orderManagement)
    {
        startPage();
        List<OrderManagement> list = orderManagementService.selectOrderManagementList(orderManagement);

        return getDataTable(list);
    }

    /**
     * 导出订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('le:management:export')")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderManagement orderManagement)
    {
        List<OrderManagement> list = orderManagementService.selectOrderManagementList(orderManagement);
        ExcelUtil<OrderManagement> util = new ExcelUtil<OrderManagement>(OrderManagement.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('le:management:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(orderManagementService.selectOrderManagementById(id));
    }

    /**
     * 新增订单管理
     */
    @PreAuthorize("@ss.hasPermi('le:management:add')")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OrderManagement orderManagement)
    {
        return toAjax(orderManagementService.insertOrderManagement(orderManagement));
    }

    /**
     * 修改订单管理
     */
    @PreAuthorize("@ss.hasPermi('le:management:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OrderManagement orderManagement)
    {
        return toAjax(orderManagementService.updateOrderManagement(orderManagement));
    }

    /**
     * 删除订单管理
     */
    @PreAuthorize("@ss.hasPermi('le:management:remove')")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(orderManagementService.deleteOrderManagementByIds(ids));
    }

    /**
     * 查询我的订单列表（小程序端使用）
     * 无需权限认证
     * 
     * @param userId 用户ID（必填）
     * @param orderStatus 订单状态（可选，1=待支付,2=待执行,3=已执行,4=已完成,5=已退款）
     * @return 订单列表
     */
    @GetMapping("/myOrders")
    public AjaxResult getMyOrders(
            @RequestParam(value = "userId", required = true) Long userId,
            @RequestParam(value = "orderStatus", required = false) String orderStatus)
    {
        List<OrderVO> list = orderManagementService.selectMyOrders(userId, orderStatus);
        return success(list);
    }

    /**
     * 取消订单（小程序端使用）
     * 无需权限认证
     * 
     * @param orderId 订单ID（必填）
     * @param cancelReason 取消原因（必填）
     * @return 结果
     */
    @PostMapping("/cancelOrder")
    public AjaxResult cancelOrder(
            @RequestParam(value = "orderId", required = true) Long orderId,
            @RequestParam(value = "cancelReason", required = true) String cancelReason)
    {
        int result = orderManagementService.cancelOrder(orderId, cancelReason);
        if (result > 0) {
            return success("订单已取消");
        } else {
            return error("取消订单失败");
        }
    }

    /**
     * 支付订单（小程序端使用）
     * 无需权限认证
     * 
     * @param orderId 订单ID（必填）
     * @return 结果
     */
    @PostMapping("/payOrder")
    public AjaxResult payOrder(
            @RequestParam(value = "orderId", required = true) Long orderId)
    {
        int result = orderManagementService.payOrder(orderId);
        if (result > 0) {
            return success("支付成功");
        } else {
            return error("支付失败");
        }
    }

    /**
     * 查询订单详情（小程序端使用）
     * 无需权限认证
     * 
     * @param orderId 订单ID（必填）
     * @return 订单详情
     */
    @GetMapping("/orderDetail")
    public AjaxResult getOrderDetail(
            @RequestParam(value = "orderId", required = true) Long orderId)
    {
        OrderVO orderDetail = orderManagementService.selectOrderDetail(orderId);
        if (orderDetail != null) {
            return success(orderDetail);
        } else {
            return error("订单不存在");
        }
    }

    /**
     * 申请退款（小程序端使用）
     * 无需权限认证
     * 
     * @param orderId 订单ID（必填）
     * @param refundReason 退款原因（必填）
     * @return 结果
     */
    @PostMapping("/refundOrder")
    public AjaxResult refundOrder(
            @RequestParam(value = "orderId", required = true) Long orderId,
            @RequestParam(value = "refundReason", required = true) String refundReason)
    {
        int result = orderManagementService.refundOrder(orderId, refundReason);
        if (result > 0) {
            return success("退款申请已提交");
        } else {
            return error("退款申请失败");
        }
    }

    /**
     * 创建服务订单（小程序端使用）
     * 用于小程序"服务"页面购买护理服务
     * 无需权限认证（前端会传递userId）
     * 
     * @param dto 订单创建DTO（包含：elderlyId、nursingItemId、expectedServiceTime、orderUserId、remark）
     * @return 订单信息（包含订单号、金额等）
     */
    @Anonymous
    @PostMapping("/wx/createOrder")
    public AjaxResult createServiceOrder(@RequestBody OrderCreateDTO dto)
    {
        try {
            OrderManagement order = orderManagementService.createServiceOrder(dto);
//            return success("下单成功", order);
            return success("下单成功");
        } catch (Exception e) {
            logger.error("创建订单失败", e);
            return error(e.getMessage());
        }
    }
}
